import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_widgets_pc/utils/ex/kq_ex.dart';

import 'package:get/get.dart';
import 'package:flutter_widgets_pc/theme/kq_theme_manager.dart';
import 'package:flutter_widgets_pc/utils/text_filed_utils.dart';

import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import '../button/kq_ink_well.dart';
import '../divider/kq_divider.dart';
import '../textFiled/kq_textfiled.dart';

/// 通用输入对话框
///
/// @author 周卓
///
class KqInputDialog extends AlertDialog {
  /// 标题
  final String? titleString;

  /// 默认值
  final String? defValue;

  /// 提示文字，默认"请输入"
  final String? placeHolder;

  /// 当行模式点击键盘换行键是否自动提交
  final bool autoSubmitWhenReturn;

  /// 是否多行，默认false
  final bool multiline;

  /// 是否启用Alt+Enter换行，如果启用，按回车就不会换行，直接提交。注意：仅[multiline]=true时生效。
  final bool altEnterNewLine;

  /// 最大行数，不传不限制
  final int? maxLines;

  /// 左边按钮文字，默认"取消"
  final String? leftBtnText;

  /// 中间按钮文字，默认null,不传则不显示
  final String? middleBtnText;

  /// 中间按钮文字颜色，默认null
  final Color? middleBtnTextColor;

  /// 左边按钮文字，默认"确定"
  final String? rightBtnText;

  /// 输入类型，默认[TextInputType.text]
  final TextInputType? inputType;

  /// 密码
  final bool password;

  /// 最大数量
  final int? maxCharCount;

  /// 输入内容限制
  final List<TextInputFormatter>? inputFormatters;

  /// 输入框文字对齐方式
  final TextAlign? inputTextAlign;

  /// 是否显示清空按钮
  final bool enableClearButton;

  /// 输入回调
  final Function(String value)? onValueChanged;

  /// 左边按钮回调
  final Function(String value)? onLeftBtnTap;

  /// 中间按钮回调
  final Function(String value)? onMiddleBtnTap;

  /// 右边按钮回调
  final Function(String value)? onRightBtnTap;

  /// 输入框内容控制器
  final TextEditingController editController;

  /// 输入框下方自定义内容
  final List<Widget>? customWidgetsBelowInput;
  final List<Widget>? customWidgetsAboveInput;

  final double? dialogWidth;
  final double? maxHeight;

  KqInputDialog(
      {Key? key,
      this.defValue,
      this.titleString,
      this.multiline = false,
      this.altEnterNewLine = false,
      this.autoSubmitWhenReturn = false,
      this.maxLines,
      this.customWidgetsAboveInput,
      this.customWidgetsBelowInput,
      this.inputFormatters,
      this.placeHolder,
      this.password = false,
      this.inputTextAlign,
      this.inputType,
      this.leftBtnText,
      this.middleBtnText,
      this.middleBtnTextColor,
      this.dialogWidth,
      this.maxHeight,
      this.rightBtnText,
      this.maxCharCount,
      this.enableClearButton = false,
      this.onValueChanged,
      this.onLeftBtnTap,
      required this.editController,
      this.onMiddleBtnTap,
      this.onRightBtnTap})
      : super(key: key) {
    if (defValue != null) {
      TextFiledUtil.setValue(editController, defValue!);
    }
  }

  void _insertNewLine() {
    final text = editController.text;
    final selection = editController.selection;
    if (!selection.isValid) return;

    final newText = text.replaceRange(selection.start, selection.end, '\n');
    final newSelection = TextSelection.collapsed(offset: selection.start + 1);

    editController.value = TextEditingValue(
      text: newText,
      selection: newSelection,
    );
  }

  void _submit() {
    if (onRightBtnTap != null) {
      onRightBtnTap!(editController.text);
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isLangScape = context.orientation == Orientation.landscape;

    final List<Widget> children = <Widget>[];

    /// 上边距
    children.add(const SizedBox(
      height: 24,
    ));

    if (titleString != null) {
      children.add(Container(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        alignment: Alignment.center,
        child: Text(
          titleString!,
          style: TextStyle(
              fontSize: 16,
              color:
                  KqThemeManager.instance.getConfig().dialogConfig.titleColor ??
                      KqThemeColors.text26,
              fontWeight: FontWeight.w600),
        ),
      ));
      children.add(const SizedBox(
        height: 24,
      ));
    }

    /// 自定义控件
    if (customWidgetsAboveInput.isNotNullOrEmpty) {
      for (var value in customWidgetsAboveInput!) {
        children.add(value);
      }
    }

    Widget etChild = KqTextFiled(
      multiline: multiline,
      useParentHeight: false,
      placeHolder: placeHolder,
      autofocus: true,
      password: password,
      contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
      controller: editController,
      maxLines: maxLines,
      maxCharCount: maxCharCount,
      inputFormatters: inputFormatters,
      enableClearButton: enableClearButton,
      onChanged: (value) {
        if (onValueChanged != null) {
          onValueChanged!(value);
        }
      },
      onSubmitted: (value) {
        if (onRightBtnTap != null && autoSubmitWhenReturn) {
          onRightBtnTap!(value);
        }
      },
      defValue: defValue,
      inputType: inputType,
      textInputAction:
          multiline ? TextInputAction.newline : TextInputAction.done,
      textAlign: inputTextAlign ?? TextAlign.start,
    );

    if (multiline && altEnterNewLine) {
      etChild = Shortcuts(
        shortcuts: <LogicalKeySet, Intent>{
          // Alt + Enter → 插入换行
          LogicalKeySet(LogicalKeyboardKey.alt, LogicalKeyboardKey.enter):
              const _AltEnterIntent(),
          // 单独 Enter → 提交
          LogicalKeySet(LogicalKeyboardKey.enter): const _SubmitIntent(),
        },
        child: Actions(
          actions: <Type, Action<Intent>>{
            _AltEnterIntent: CallbackAction<_AltEnterIntent>(
              onInvoke: (intent) => _insertNewLine(),
            ),
            _SubmitIntent: CallbackAction<_SubmitIntent>(
              onInvoke: (intent) => _submit(),
            ),
          },
          child: etChild,
        ),
      );
    }

    /// 输入框
    children.add(Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
          border: Border.all(
              width: 1,
              color:
                  KqThemeManager.instance.getConfig().commonConfig.lineColor ??
                      KqThemeColors.lineColor),
          color: KqThemeColors.bgTransparent),
      child: etChild,
    ));

    /// 自定义控件
    if (customWidgetsBelowInput.isNotNullOrEmpty) {
      for (var value in customWidgetsBelowInput!) {
        children.add(value);
      }
    }

    /// 下边距
    children.add(const SizedBox(
      height: 24,
    ));

    /// 按钮
    children.add(const KqDivider());

    children.add(Row(
      children: [
        Expanded(
            child: KqInkWell(
          onTap: () {
            if (onLeftBtnTap != null) {
              onLeftBtnTap!(editController.text);
            }
          },
          child: Container(
            alignment: Alignment.center,
            width: double.infinity,
            height: 48,
            child: Text(
              leftBtnText ?? KqIntl.currentResource.cancel,
              style: TextStyle(
                  fontSize: 16,
                  color: KqThemeManager.instance
                          .getConfig()
                          .dialogConfig
                          .cancelBtnColor ??
                      KqThemeColors.text8C),
            ),
          ),
        )),
        const KqVerticalDivider(
          height: 48,
        ),
        Visibility(
            visible: middleBtnText != null,
            child: Expanded(
              child: KqInkWell(
                onTap: () {
                  if (onMiddleBtnTap != null) {
                    onMiddleBtnTap!(editController.text);
                  }
                },
                child: Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  height: 48,
                  child: Text(
                    middleBtnText ?? '',
                    style: TextStyle(
                        fontSize: 16,
                        color: middleBtnTextColor ??
                            KqThemeManager.instance
                                .getConfig()
                                .dialogConfig
                                .middleBtnColor ??
                            KqThemeColors.text8C),
                  ),
                ),
              ),
            )),
        Visibility(
          visible: middleBtnText != null,
          child: const KqVerticalDivider(
            height: 48,
          ),
        ),
        Expanded(
            child: KqInkWell(
          onTap: () {
            if (onRightBtnTap != null) {
              onRightBtnTap!(editController.text);
            }
          },
          child: Container(
            alignment: Alignment.center,
            width: double.infinity,
            height: 48,
            child: Text(
              rightBtnText ?? KqIntl.currentResource.confirm,
              style: TextStyle(
                  fontSize: 16,
                  color: KqThemeManager.getDialogConfig().mainBtnColor ??
                      KqThemeColors.textLightBlue),
            ),
          ),
        ))
      ],
    ));

    Widget dialogChild = Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: children,
    );
    var padding = MediaQuery.of(context).viewInsets.bottom;
    return UnconstrainedBox(
        child: Padding(
      padding: EdgeInsets.only(bottom: padding),
      child: SizedBox(
          width: dialogWidth ?? 320,
          child: Material(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(
                      KqThemeManager.instance.getConfig().dialogConfig.radius ??
                          8))),
              color: KqThemeManager.getDialogConfig().bgColor ??
                  KqThemeColors.bgWhite,
              child: multiline && maxLines != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(
                          KqThemeManager.instance
                                  .getConfig()
                                  .dialogConfig
                                  .radius ??
                              8)),
                      child: dialogChild,
                    )
                  : LimitedBox(
                      maxHeight: maxHeight ?? (isLangScape ? 350 : 400),
                      child: ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(
                            KqThemeManager.instance
                                    .getConfig()
                                    .dialogConfig
                                    .radius ??
                                8)),
                        child: dialogChild,
                      ),
                    ))),
    ));
  }
}

/// 定义两个 Intent
class _AltEnterIntent extends Intent {
  const _AltEnterIntent();
}

class _SubmitIntent extends Intent {
  const _SubmitIntent();
}
